<template>
    <div id="warehouse_manage">
        <div class="container">
            <div class="handle-box">
                <el-form ref="form" :inline="true" :model="form">
                    <el-form-item>
                        <el-button type="success" @click="handleWarehouseApp">入库申请</el-button>
                    </el-form-item>

                    <el-form-item label="">
                        <el-input
                            placeholder="名称"
                            @keyup.native.enter="handleSearch"
                            clearable
                            v-model="query.name"
                            @clear="handleSearch"
                            class="handle-input mr10"
                        ></el-input>
                    </el-form-item>

                    <el-form-item label="">
                        <el-input
                            @keyup.native.enter="handleSearch"
                            clearable
                            @clear="handleSearch"
                            v-model="query.jobCode"
                            placeholder="批次号"
                            class="handle-input mr10"
                        ></el-input>
                    </el-form-item>

                    <el-form-item label="">
                        <el-select
                            @change="handleSearch"
                            v-model="query.checkStatus"
                            placeholder="审核状态"
                            :clearable="true"
                            class="handle-select mr10"
                        >
                            <el-option key="1" label="待审核" :value="1"></el-option>
                            <el-option key="2" label="审核不通过" :value="2"></el-option>
                            <el-option key="-1" label="退回修改" :value="-1"></el-option>
                            <el-option key="4" label="审核通过" :value="4"></el-option>
                            <el-option key="5" label="产品上线" :value="5"></el-option>
                            <el-option key="-2" label="重提待审" :value="-2"></el-option>
                            <el-option key="-9" label="产品下线" :value="-9"></el-option>
                            <el-option key="6" label="音源审核通过" :value="6"></el-option>

                            <!-- <el-option key="0" label="回退" :value="0"></el-option> -->
                        </el-select>
                    </el-form-item>

                    <!-- <el-form-item label="操作者:">
                        <el-input v-model="query.name" placeholder="" class="handle-input mr10"></el-input>
                    </el-form-item> -->

                    <el-form-item>
                        <el-button :disabled="disabled" type="primary" @click="handleSearch">
                            <!-- 查询 -->
                            {{ $t('m.queryBtn') }}
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>

                <el-table-column width="auto" label="批次号" align="center" :show-overflow-tooltip="true">
                    <template slot-scope="scope">{{ scope.row.jobCode }}</template>
                </el-table-column>

                <el-table-column width="auto" label="名称" align="center" :show-overflow-tooltip="true">
                    <template slot-scope="scope">{{ scope.row.name }}</template>
                </el-table-column>

                <el-table-column width="auto" label="申请类型" align="center" :show-overflow-tooltip="true">
                    <template slot-scope="scope">{{
                        scope.row.applyType == 1 ? '常规上线' : scope.row.applyType == 3 ? '紧急上线' : ''
                    }}</template>
                </el-table-column>

                <el-table-column width="auto" label="歌曲数" align="center" :show-overflow-tooltip="true">
                    <template slot-scope="scope">{{ scope.row.songNumber }}</template>
                </el-table-column>

                <el-table-column width="auto" label="创建时间" align="center" :show-overflow-tooltip="true">
                    <template slot-scope="scope">{{ scope.row.createTime }}</template>
                </el-table-column>

                <el-table-column width="auto" label="审核结果" align="center" :show-overflow-tooltip="true">
                    <template slot-scope="scope">{{
                        scope.row.checkStatus == 1
                            ? '待审核'
                            : scope.row.checkStatus == 2
                            ? '版权审核不通过'
                            : scope.row.checkStatus == -1
                            ? '退回修改'
                            : scope.row.checkStatus == 4
                            ? '版权审核通过'
                            : scope.row.checkStatus == 5
                            ? '产品上线'
                            : scope.row.checkStatus == -2
                            ? '重提待审'
                            : scope.row.checkStatus == -9
                            ? '产品下线'
                            : scope.row.checkStatus == 6
                            ? '音源审核通过'
                            : scope.row.checkStatus == 0
                            ? '回退'
                            : scope.row.checkStatus == 3
                            ? '物料匹配中'
                            : scope.row.checkStatus == 7
                            ? '入库中'
                            : ''
                    }}</template>
                </el-table-column>

                <el-table-column width="auto" label="待处理事项" align="center" :show-overflow-tooltip="true">
                    <!-- <template slot-scope="scope">{{ scope.row.remark }}</template> -->

                    <template slot-scope="scope" v-if="scope.row.copyrightStatus == 6">
                        <el-button type="primary" size="mini">{{ scope.row.remark }}</el-button>
                    </template>
                    <template slot-scope="scope" v-if="scope.row.copyrightStatus != 6">{{ scope.row.remark }}</template>

                    <template slot-scope="scope">
                        <span>{{ scope.row.remark }}</span>
                        <br />
                        <el-button @click="handleDetail(scope.$index, scope.row)" v-if="scope.row.checkStatus == 0" type="text" size="mini"
                            >详情</el-button
                        >
                    </template>
                </el-table-column>

                <!-- <el-table-column width="auto" label="操作者" align="center">
                    <template slot-scope="scope">{{ scope.row.creator }}</template>
                </el-table-column> -->

                <el-table-column width="auto" label="管理" align="center">
                    <template slot-scope="scope">
                        <el-button
                            v-if="scope.row.checkStatus == 1"
                            type="warning"
                            size="mini"
                            @click="handleAudit(scope.$index, scope.row)"
                            >审核</el-button
                        >
                        <el-button
                            v-if="scope.row.checkStatus == 6"
                            type="primary"
                            size="mini"
                            @click="handleWarehousing(scope.$index, scope.row)"
                            >入库</el-button
                        >

                        <el-button
                            v-if="scope.row.checkStatus == -1"
                            type="primary"
                            size="mini"
                            @click="handleEdit(scope.$index, scope.row)"
                        >
                            <!-- 编辑 -->
                            {{ $t('m.editBtn') }}
                        </el-button>

                        <el-button
                            @click="handleMatchMaterial(scope.$index, scope.row)"
                            v-if="[4, 0].includes(scope.row.checkStatus)"
                            type="primary"
                            size="mini"
                            >匹配物料</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination">
                <el-pagination
                    background
                    layout="total,sizes, prev, pager, next, jumper"
                    :page-sizes="[5, 10, 20, 30]"
                    @size-change="handleSizeChange"
                    :current-page="query.pageIndex"
                    :page-size="query.pageSize"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>
        <!-- 详情弹出框 -->
        <el-dialog title="物料匹配详情" :visible.sync="detailVisible" width="50%">
            <div
                :style="{
                    overflow: 'auto',
                    'max-height': '480px'
                }"
            >
                <el-table :data="tableData_" border class="table" ref="multipleTable" header-cell-class-name="table-header">
                    <el-table-column label="歌曲名" align="center" :show-overflow-tooltip="true">
                        <template slot-scope="scope">{{ scope.row.songName }}</template>
                    </el-table-column>

                    <el-table-column label="歌手名" align="center" :show-overflow-tooltip="true">
                        <template slot-scope="scope">{{ scope.row.actorName }}</template>
                    </el-table-column>

                    <el-table-column label="专辑名" align="center" :show-overflow-tooltip="true">
                        <template slot-scope="scope">{{ scope.row.albumName }}</template>
                    </el-table-column>

                    <el-table-column label="匹配结果" align="center" :show-overflow-tooltip="true">
                        <template>{{ '失败' }}</template>
                    </el-table-column>
                    <el-table-column label="备注" align="center" :show-overflow-tooltip="true">
                        <template slot-scope="scope">{{ scope.row.checkResult }}</template>
                    </el-table-column>
                </el-table>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="detailVisible = false">关闭</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
  import NProgress from 'nprogress';
  import { debounce, throttle } from '@/utils/utils.js';
  import { mapGetters, mapMutations } from 'vuex';
  export default {
      name: 'WarehouseManage',
      data() {
          return {
              disabled: false,
              // query: {
              //     pageIndex: 1,
              //     pageSize: 10,
              //     jobCode: '',
              //     name: '',
              //     checkStatus: ''
              // },
              detailVisible: false,
              // tableData: [],
              tableData_: [],
              // pageTotal: 0,
              // pageTotal_: 0,
              form: {}
          };
      },
      // activated() {
      //     this.getData();
      // },
      computed: {
          ...mapGetters({
              tableData: 'getWarehouseManageData',
              query: 'getWarehouseManageQuery',
              pageTotal: 'getWarehouseManagePageTotal'
          })
      },
      watch: {
          $route: {
              deep: true,
              immediate: true,
              handler(a, b) {
                  console.log(a, b);
                  if (a.name === 'WarehouseManage') {
                      if (Object.keys(this.tableData).length === 0) {
                          this.getData();
                      }
                  }
              }
          }
      },
      methods: {
          ...mapMutations({
              SET_AUDIT_EDIT_FORM: 'SET_AUDIT_EDIT_FORM',
              SET_AUDIT_DETAILS_FORM: 'SET_AUDIT_DETAILS_FORM',
              SET_WAREHOUSE_MANAGE_DATA: 'SET_WAREHOUSE_MANAGE_DATA',
              SET_WAREHOUSE_MANAGE_PAGETOTAL: 'SET_WAREHOUSE_MANAGE_PAGETOTAL',
              SET_WAREHOUSE_MANAGE_QUERY: 'SET_WAREHOUSE_MANAGE_QUERY'
          }),
          async getData() {
              try {
                  NProgress.start();
                  this.disabled = true;
                  let url = '/job/jobs';
                  let headers = {};
                  if (localStorage.getItem('roles') && JSON.parse(localStorage.getItem('roles')).includes('CPOA')) {
                      headers['cppname'] = encodeURIComponent(localStorage.getItem('ms_username'));
                  }
                  let { data: res } = await this.$http[1].get(url, {
                      params: this.$removeField({
                          page: this.query.pageIndex,
                          size: this.query.pageSize,
                          jobCode: this.query.jobCode.trim(),
                          name: this.query.name.trim(),
                          checkStatus: this.query.checkStatus
                      }),
                      // headers: {
                      //     cppname:
                      //         localStorage.getItem('roles') && JSON.parse(localStorage.getItem('roles')).includes('CPOA')
                      //             ? localStorage.getItem('ms_username')
                      //             : null
                      // }
                      headers
                  });
                  if (res.code != '0000') {
                      throw new Error(res.message);
                  }
                  console.log('入库管理', res);
                  if (res.data.content && res.data.content.length > 0) {
                      res.data.content.map((item) => {
                          item.createTime = this.$dateFormat(item.createTime, '', '-');
                      });
                      this.SET_WAREHOUSE_MANAGE_DATA(res.data.content);
                      this.SET_WAREHOUSE_MANAGE_PAGETOTAL(res.data.totalElements);
                  } else {
                      this.SET_WAREHOUSE_MANAGE_DATA([]);
                      this.SET_WAREHOUSE_MANAGE_PAGETOTAL(0);
                  }
                  NProgress.done();
                  this.disabled = false;
              } catch (err) {
                  console.log(err);
                  this.SET_WAREHOUSE_MANAGE_DATA([]);
                  this.SET_WAREHOUSE_MANAGE_PAGETOTAL(0);
                  NProgress.done();
                  this.disabled = false;
                  this.$message.error({
                      message: err.message,
                      duration: 1500
                  });
              }
          },
          // 触发搜索按钮
          // handleSearch() {
          //     this.$set(this.query, 'pageIndex', 1);
          //     this.getData();
          // },
          handleSearch: debounce(function () {
              this.$set(this.query, 'pageIndex', 1);
              this.getData();
          }, 300),
          // 入库申请
          handleWarehouseApp() {
              this.$router.replace({
                  path: '/warehouse_/app'
              });
          },
          // 入库
          async handleWarehousing(index, row) {
              try {
                  let url = '/job/valided';
                  let { data: res } = await this.$http[1].post(url, `jobCode=${row.jobCode}`, {
                      headers: {
                          'Content-Type': 'application/x-www-form-urlencoded'
                      }
                  });
                  console.log(res);
                  this.$message.success({
                      duration: 1500,
                      message: res.message
                  });
                  this.getData();
              } catch (err) {
                  console.dir(err);
                  this.$message.error({
                      message: err.message,
                      duration: 1500
                  });
              }
          },
          // 详情
          async handleDetail(index, row) {
              try {
                  let url = '/job/invalidDetails';
                  let { data: res } = await this.$http[0].get(url, {
                      params: {
                          jobId: row.id
                      }
                  });
                  console.log(res);
                  if (res.code != '0000') {
                      throw new Error(res.message);
                  }
                  if (res.data && res.data.length > 0) {
                      this.tableData_ = res.data;
                      // this.pageTotal_ = res.data.totalElements;
                  } else {
                      this.tableData_ = [];
                      // this.pageTotal_ = 0;
                  }
              } catch (err) {
                  console.dir(err);
                  this.tableData_ = [];
                  // this.pageTotal_ = 0;
                  this.$message.error({
                      message: err.message,
                      duration: 1500
                  });
              }
              this.detailVisible = true;
          },
          // 审核
          handleAudit(index, row) {
              this.SET_AUDIT_DETAILS_FORM({});
              this.$router.replace({
                  path: '/warehouse_/details',
                  query: {
                      id: row.id
                  }
              });
              localStorage.setItem('id_warehouse', row.id);
          },
          // 编辑
          handleEdit(index, row) {
              this.SET_AUDIT_EDIT_FORM({});
              this.$router.replace({
                  path: '/warehouse_/edit',
                  query: {
                      id: row.id
                  }
              });
              localStorage.setItem('id_warehouse', row.id);
          },
          // 匹配物料
          handleMatchMaterial(index, row) {
              console.log(index, row);
              this.$confirm('确定要匹配吗？', '提示', {
                  type: 'warning'
              })
                  .then(() => {
                      this.matchMaterial(index, row);
                  })
                  .catch(() => {});
          },
          async matchMaterial(index, row) {
              try {
                  NProgress.start();
                  let url = '/job/validResource';
                  var formdata = new FormData();
                  formdata.append('jobCode', row.jobCode);
                  // formdata.append('auditFlag', row.auditFlag);
                  if (row.remark) {
                      formdata.append('remark', row.remark);
                  } else {
                      formdata.append('remark', '');
                  }

                  let { data: res } = await this.$http[1].post(url, formdata, {
                      headers: {
                          'Content-Type': 'multipart/form-data'
                      }
                  });

                  console.log(res);
                  this.getData();
                  this.$message.success({
                      message: res.message,
                      duration: 1500
                  });
                  // this.$router.replace({
                  //     path: '/warehouse_/manage'
                  // });
                  NProgress.done();
              } catch (err) {
                  console.dir(err);
                  NProgress.done();
                  this.$message.error({
                      message: err.message,
                      duration: 1500
                  });
              }
          },
          // 多选操作
          handleSelectionChange(val) {},

          // 分页导航
          handlePageChange(val) {
              this.$set(this.query, 'pageIndex', val);
              this.getData();
          },
          handleSizeChange(val) {
              this.$set(this.query, 'pageSize', val);
              this.getData();
          }
      }
  };
</script>

<style lang="scss">
  #warehouse_manage {
      .table-header {
          .cell {
              white-space: nowrap !important;
          }
      }
      .handle-box {
          margin-bottom: 20px;
          .el-form {
              display: grid;
              grid-auto-flow: column;
              justify-content: flex-start;
              .el-form-item {
                  width: 95%;
                  .el-form-item__content {
                      .el-select,
                      .handle-input {
                          width: 100%;
                      }
                  }
              }
          }
      }

      .handle-select {
          width: 120px;
      }

      .handle-input {
          /* width: 300px; */
          width: 69px;
          height: 28px;
          display: inline-block;
      }
      .table {
          width: 100%;
          font-size: 14px;
      }
      /* .red {
          color: #ff0000;
      } */
      .mr10 {
          margin-right: 10px;
      }
      .table-td-thumb {
          display: block;
          margin: auto;
          width: 40px;
          height: 40px;
      }
  }
</style>
